<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-brandNames
  brandName: "Menu",
  inheritAttrs: false,
});

import { MenuQuery, MenuForm, MenuVO } from "@/api/menu/types";
import {
  listMenus,
  getBrandForm,
  getMenuOptions,
  addMenu,
  deleteMenu,
  updateMenu,
} from "@/api/brand";

import { MenuTypeEnum } from "@/enums/MenuTypeEnum";

import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";
import SingleUpload from "@/components/Upload/SingleUpload.vue";
const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive({
  title: "",
  brandName: "",
  brandLogo: "",
  visible: false,
});

const queryParams = reactive<MenuQuery>({});
const menuList = ref<MenuVO[]>([]);

const menuOptions = ref<OptionType[]>([]);

const formData = reactive<MenuForm>({
  parentBrandId: 0,
  brandId: 0,
  brandLogo: "",
  brandName: "",
  visible: 1,
  authPrice: 0,
  sort: 1,
  type: MenuTypeEnum.MENU,
  alwaysShow: 0,
  keepAlive: 0,
});

const rules = reactive({
  parentBrandId: [
    { required: true, message: "请选择顶级品牌", trigger: "blur" },
  ],
  brandName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择品牌类型", trigger: "blur" }],
  path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],

  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  visible: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
});

// 选择表格的行品牌ID
const selectedRowMenuId = ref<number | undefined>();

const menuCacheData = reactive({
  type: "",
  path: "",
});

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  listMenus(queryParams)
    .then(({ data }) => {
      menuList.value = data;
    })
    .then(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**行点击事件 */
function onRowClick(row: any) {
  selectedRowMenuId.value = row.brandId;
}

/**
 * 打开表单弹窗
 *
 * @param parentBrandId 父品牌ID
 * @param menuId 品牌ID
 */
function openDialog(
  parentBrandId?: number,
  menuId?: number,
  isLastLevel?: number
) {
  if (parentBrandId != 10000000) {
    getMenuOptions()
      .then(({ data }) => {
        menuOptions.value = [{ value: 0, label: "顶级品牌", children: data }];
      })
      .then(() => {
        dialog.visible = true;
        if (menuId) {
          dialog.title = "编辑品牌";
          getBrandForm(menuId).then(({ data }) => {
            Object.assign(formData, data);
            menuCacheData.type = data.type;
            menuCacheData.path = data.path ?? "";
          });

          if (isLastLevel != 3) {
            dialog.title = "新增品牌";
            dialog.brandName = "品牌名称";
            dialog.brandLogo = "品牌logo";
          } else {
            dialog.title = "新增车型";
            dialog.brandName = "车型名称";
            dialog.brandLogo = "车型图片";
          }
        } else {
          if (isLastLevel != 3) {
            dialog.title = "新增品牌";
            dialog.brandName = "品牌名称";
            dialog.brandLogo = "品牌logo";
          } else {
            dialog.title = "新增车型";
            dialog.brandName = "车型名称";
            dialog.brandLogo = "车型图片";
          }
          formData.parentBrandId = parentBrandId;
          formData.brandLogo = "";
        }
      });
  } else {
    dialog.visible = true;
    dialog.title = "新增分类";
    dialog.brandName = "分类名称";
  }
}

/** 品牌类型切换事件处理 */
function onMenuTypeChange() {
  // 如果品牌类型改变，清空路由路径；未改变在切换后还原路由路径
  if (formData.type !== menuCacheData.type) {
    formData.path = "";
  } else {
    formData.path = menuCacheData.path;
  }
}

/** 品牌保存提交 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.id;
      if (menuId) {
        if (formData != undefined) {
          updateMenu(menuId, formData).then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          });
        }
      } else {
        if (formData != undefined) {
          addMenu(formData).then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          });
        }
      }
    }
  });
}

/** 删除品牌 */
function handleDelete(menuId: number) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteMenu(menuId).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.brandId = 0;
  formData.brandLogo = "";
  formData.parentBrandId = 0;
  formData.visible = 1;
  formData.sort = 1;
  formData.perm = undefined;
  formData.component = undefined;
  formData.path = undefined;
  formData.redirect = undefined;
  formData.alwaysShow = undefined;
  formData.keepAlive = undefined;
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="品牌名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:menu:add']"
          type="success"
          @click="openDialog(10000000)"
        >
          <template #icon><i-ep-plus /></template>
          新增分类</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="menuList"
        highlight-current-row
        row-key="brandId"
        :expand-row-keys="['1']"
        @row-click="onRowClick"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <!-- <el-table-column align="center" label="序号"  width="150">
        </el-table-column> -->

        <el-table-column label="品牌名称">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.icon" />

            <el-tag
              v-if="scope.row.parentBrandId === 0"
              type="warning"
              style="background: red; color: #fff"
              >{{ scope.row.inDx }} {{ scope.row.brandName }}</el-tag
            >
            <el-tag
              v-if="scope.row.parentBrandId != 0 && scope.row.isLastLevel != 0"
              type="danger"
              style="background: blue; color: #fff"
              >{{ scope.row.inDx }} {{ scope.row.brandName }}</el-tag
            >

            <el-tag
              v-if="scope.row.isLastLevel == 0"
              type="danger"
              style="background: green; color: #fff"
              >{{ scope.row.inDx }} {{ scope.row.brandName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="排序字段" prop="sort"> </el-table-column>
        <el-table-column label="类型" align="center">
          <template #default="scope">
            <el-tag
              v-if="scope.row.parentBrandId === 0"
              type="warning"
              style="background: red; color: #fff"
              >分类</el-tag
            >
            <el-tag
              v-if="scope.row.parentBrandId != 0 && scope.row.isLastLevel != 0"
              type="danger"
              style="background: blue; color: #fff"
              >品牌</el-tag
            >

            <el-tag
              v-if="scope.row.isLastLevel == 0"
              type="danger"
              style="background: green; color: #fff"
              >车型</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="品牌/车型图片" align="center" prop="brandLogo">
          <template #default="scope">
            <span><img :src="scope.row.brandLogo" style="height: 60px" /></span>
          </template>
        </el-table-column>

        <el-table-column label="认证金额">
          <template #default="scope">
            {{ scope.row.authPrice }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" align="right" label="操作" width="280">
          <template #default="scope">
            <el-button
              v-if="
                (scope.row.type == 'CATALOG' || scope.row.isLastLevel != 0) &&
                scope.row.parentBrandId === 0
              "
              v-hasPerm="['sys:menu:add']"
              type="primary"
              style="background: red; color: #fff; margin: 10px; padding: 5px"
              link
              size="small"
              @click.stop="
                openDialog(scope.row.brandId, 0, scope.row.isLastLevel)
              "
            >
              <i-ep-plus />
              新增品牌
            </el-button>
            <el-button
              v-if="
                (scope.row.type == 'CATALOG' || scope.row.isLastLevel != 0) &&
                scope.row.parentBrandId != 0 &&
                scope.row.isLastLevel != 0
              "
              v-hasPerm="['sys:menu:add']"
              type="primary"
              style="background: blue; color: #fff; margin: 10px; padding: 5px"
              link
              size="small"
              @click.stop="
                openDialog(scope.row.brandId, 0, scope.row.isLastLevel)
              "
            >
              <i-ep-plus />
              新增车型
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:edit']"
              v-if="scope.row.parentBrandId === 0"
              type="primary"
              style="background: red; color: #fff; margin: 10px; padding: 5px"
              link
              size="small"
              @click.stop="
                openDialog(undefined, scope.row.brandId, scope.row.isLastLevel)
              "
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:edit']"
              v-if="scope.row.parentBrandId != 0 && scope.row.isLastLevel != 0"
              type="primary"
              style="background: blue; color: #fff; margin: 10px; padding: 5px"
              link
              size="small"
              @click.stop="
                openDialog(undefined, scope.row.brandId, scope.row.isLastLevel)
              "
            >
              <i-ep-edit />编辑

              <span v-if="scope.row.isLastLevel == 0" style="color: green"
                ><i-ep-edit />编辑</span
              >
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:edit']"
              v-if="scope.row.isLastLevel == 0"
              type="primary"
              style="background: green; color: #fff; margin: 10px; padding: 5px"
              link
              size="small"
              @click.stop="
                openDialog(undefined, scope.row.brandId, scope.row.isLastLevel)
              "
            >
              <i-ep-edit />编辑
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:delete']"
              v-if="scope.row.parentBrandId === 0"
              type="primary"
              link
              style="background: red; color: #fff; margin: 10px; padding: 5px"
              size="small"
              @click.stop="handleDelete(scope.row.brandId)"
            >
              <i-ep-delete /> 删除
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:delete']"
              type="primary"
              link
              size="small"
              v-if="scope.row.parentBrandId != 0 && scope.row.isLastLevel != 0"
              style="background: blue; color: #fff; margin: 10px; padding: 5px"
              @click.stop="handleDelete(scope.row.brandId)"
            >
              <i-ep-delete />
              删除
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:delete']"
              type="primary"
              link
              size="small"
              v-if="scope.row.isLastLevel == 0"
              style="background: green; color: #fff; margin: 10px; padding: 5px"
              @click.stop="handleDelete(scope.row.brandId)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      destroy-on-close
      append-to-body
      width="1000px"
      @close="closeDialog"
      top="5vh"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="160px"
      >
        <el-form-item
          v-if="dialog.brandName != '车型名称' && dialog.title != '新增分类'"
          label="品牌"
          prop="parentBrandId"
        >
          <el-tree-select
            v-model="formData.parentBrandId"
            placeholder="选择上级品牌"
            :data="menuOptions"
            disabled="disabled"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item
          v-if="dialog.brandName == '车型名称' && dialog.title != '新增分类'"
          label="品牌"
          prop="parentBrandId"
        >
          <el-tree-select
            disabled="disabled"
            v-model="formData.parentBrandId"
            placeholder="选择上级品牌"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item :label="dialog.brandName" prop="brandName">
          <el-input v-model="formData.brandName" placeholder="请输入品牌名称" />
        </el-form-item>

        <el-form-item
          label="认证价格"
          prop="authPrice"
          v-if="dialog.title != '新增分类'"
        >
          <el-input v-model="formData.authPrice" placeholder="请输入认证价格" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入认证价格" />
        </el-form-item>

        <el-form-item
          :label="dialog.brandLogo"
          prop="type"
          v-if="dialog.title != '新增分类'"
        >
          <single-upload v-model="formData.brandLogo" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
